from Verification import Verification
from DBUtility import DBManage


class User:
    def __init__(self, job_module):
        self.condition = None
        self.employID = None
        self.username = None
        self.phone = None
        self.department = None
        self.job = None
        self.password = None
        self.verify = Verification()
        self.db = DBManage()
        self.recruit = job_module
        self.recruit.set_user_data(self)

    def main_view(self):
        """主界面"""
        while True:
            choice = input("""\033[36m
            欢迎使用用户系统
              1.登录
              2.注册
              0.退出
            请选择操作:\033[0m""")
            try:
                if choice == "1":
                    self.login()
                elif choice == "2":
                    self.register()
                elif choice == "0":
                    return
                else:
                    print("\033[31m无效选择，请重新输入！\033[0m")
            except:
                pass

    def personal_center(self):
        """个人中心"""
        while True:
            choice = input(f"""\033[35m
            欢迎, {self.username}
              我的信息:
            用户名: {self.username}
            手机号: {self.phone}
            工号: {self.employID}
            职位：{self.job}
            部门：{self.department}\033[36m

             1.修改账密
             2.注销账号
             3.查看招聘信息
             4.求职
             5.查看求职回执
             6.员工系统
             0.退出登录
            请选择操作：\033[0m""")
            try:
                if choice == "1":
                    self.update_credentials()
                    return
                elif choice == "2":
                    self.confirm_logout()
                    return
                elif choice == "3":
                    self.recruit.show_job()
                elif choice == "4":
                    self.recruit.get_job()
                elif choice == "5":
                    self.recruit.show_resume()
                elif choice == "6":
                    if self.employID:
                        self.employee_system()
                    else:
                        print("您还没有入职！不能使用员工系统！")
                elif choice == "0":
                    self.db.refresh_connection()  # 刷新连接
                    return
                else:
                    print("\033[31m无效选择，请重新输入！\033[0m")
            except:
                pass

    def employee_system(self):
        """员工系统"""
        while True:
            choice = input(f"""\033[35m
            欢迎,{self.employID}\033[36m
              1.签到
              2.请假
              3.查看请假回执
              4.查看个人记录
              0.返回
            请选择操作:\033[0m""")
            try:
                if choice == "1":
                    self.recruit.sign_in()
                elif choice == "2":
                    self.recruit.leave()
                elif choice == "3":
                    self.recruit.leave_receipt()
                elif choice == "4":
                    self.recruit.show_personal()
                elif choice == "0":
                    return
                else:
                    print("\033[31m无效选择，请重新输入！\033[0m")
            except:
                pass

    def fetch_user_info(self, phone):
        """获取用户信息"""
        try:
            condition = f"phone='{phone}'"
            result = self.db.select_data('tb_user', condition)
            if result:
                self.employID, self.username, self.phone, self.job, self.department, self.password = result[0][1:7]
                self.condition = f"employID={self.employID}"
            else:
                raise Exception("未找到用户信息")
        except Exception as e:
            print(f"\033[31m{e}\033[0m")

    def login(self):
        """登录"""
        phone = input("请输入手机号：")
        password = input("请输入密码：")
        args = [phone, password]
        try:
            if self.verify.enter_validation(*args):  # 输入校验
                if self.verify.login_verify('tb_user', phone, password):  # 登录校验
                    self.fetch_user_info(phone)  # 一登陆就获取用户信息
                    self.personal_center()
        except Exception as e:
            print(f"登录失败: \033[31m{e}\033[0m")

    def register(self):
        """注册"""
        username = input("请输入用户名：")
        phone = input("请输入手机号：")
        password = input("请输入密码：")
        args = [username, phone, password]
        try:
            if self.verify.enter_validation(*args):
                password_h = self.verify.hash_password(password)
                # 进行状态检查
                condition = f"name = '{username}' and phone = '{phone}' and state = '0'"
                if self.db.select_data('tb_user', condition):
                    # 更改密码和状态
                    self.db.update_data('tb_user', {'password': password_h, 'state': '1'}, condition)
                    print("注册成功!")
                elif self.verify.register_verify(phone, password):  # 注册校验
                    datas = {'name': username, 'phone': phone, 'password': password_h}
                    self.db.add_data('tb_user', datas)
                    print("注册成功！")
        except Exception as e:
            print(f"\033[31m{e}\033[0m")

    def update_credentials(self):
        """修改手机号和密码"""
        password = input("请输入现有密码: ")
        try:
            if self.verify.hash_password(password) == self.password:
                new_phone = input("请输入新的手机号：")
                new_password = input("请输入新密码：")
                args = [new_phone, new_password]
                if self.verify.enter_validation(*args):  # 输入检验
                    if self.verify.register_verify(new_phone, new_password):  # 注册校验
                        # 条件
                        condition = f"phone = '{self.phone}'"
                        datas = {'phone': new_phone}
                        # 修改相关表中的手机号
                        self.db.update_data('tb_employee', datas, condition)
                        self.db.update_data('tb_resume', datas, condition)
                        self.db.update_data('tb_leave', datas, condition)

                        # 对密码进行hash加密
                        pwd = self.verify.hash_password(new_password)
                        datas = {'phone': new_phone, 'password': pwd}
                        self.db.update_data("tb_user", datas, condition)
                        print("修改成功！请重新登录！")
                        return
                    else:
                        print("新手机号已被注册!")
            else:
                print("密码错误")
        except Exception as e:
            print(f"信息修改失败: \033[31m{e}\033[0m")
        self.personal_center()  # 输入性错误返回原界面

    def confirm_logout(self):
        """账号注销"""
        choice = input("确认要注销该账号吗？输入 '(Y/y)' 确认，其它键取消：").lower()
        if choice == 'y':
            password = input("请输入密码以确认注销：")
            try:
                if self.verify.enter_validation(password):  # 输入校验
                    # 修改状态
                    condition = f"phone = '{self.phone}'"
                    datas = {'state': '0'}
                    self.db.update_data('tb_user', datas, condition)
                    print("账号已注销！")
                    return
            except Exception as e:
                print(f"注销失败: \033[31m{e}\033[0m'")
        else:
            print("已取消注销")
        self.personal_center()  # 输入性错误返回原界面


class JobModule:
    def __init__(self):
        self.db = DBManage()
        self.verify = Verification()
        self.data = None

    def set_user_data(self, user):
        """设置user属性"""
        self.data = user

    def show_job(self):
        """显示所有招聘信息，支持筛选"""
        try:
            print(self.db.show_data('tb_recruit'))
        except Exception as e:
            print(f"显示招聘信息失败: \033[31m{e}\033[0m'")

    def get_job(self):
        """求职"""
        # 确保还没有入职！
        if self.data.employID is None:
            try:
                job_id = int(input("请输入职业编号:"))
                if self.verify.enter_validation(job_id):
                    condition = f"id = {job_id}"
                    # 查找职位
                    result = self.db.select_data('tb_recruit', condition)
                    if result:
                        job = result[0][1]  # 获取职位
                        salary = result[0][3]  # 获取底薪
                        print(result)  # 展示查到的职位！
                        choice = input('确定求职吗？(Y/y) or (N/n):').lower()
                        if choice == 'y':
                            # 如果查到 手机号 和 pass 字段为 NULL 则 不能再次提交
                            condition = f"phone = '{self.data.phone}' and pass is NULL"
                            resume_check = self.db.select_data('tb_resume', condition)
                            if resume_check:
                                print("已经提交一份简历！不能重复提交！")
                            else:
                                info = input("请输入您的个人简述(简历): ")
                                if self.verify.enter_validation(info):
                                    # 将简历存入“缓存” 数据库中!
                                    datas = {'name': self.data.username, 'phone': self.data.phone, 'job': job,
                                             'salary': salary, 'info': info}
                                    self.db.add_data('tb_resume', datas)
                                    # 将简历存入永久性数据库中！
                                    self.db.add_data('tb_resumes', datas)
                                    print("简历投递成功！")
                        elif choice == 'n':
                            print("已取消求职！")
                        else:
                            print("\033[31m无效选择，请重新输入！\033[0m")
                    else:
                        print("未找到该职位！")
            except Exception as e:
                print(f"\033[31m{e}\033[0m'")
        else:
            print("您已经入职！")

    def show_resume(self):
        """查看个人求职结果"""
        try:
            condition = f"phone = '{self.data.phone}'"
            result = self.db.select_data('tb_resume', condition)
            if result:
                print(result)
            else:
                print("您还没有投递简历！")
        except Exception as e:
            print(f"查询失败: \033[31m{e}\033[0m'")

    def incumbency(self):
        """判断是否在职"""
        return self.db.select_data('tb_employee', self.data.condition)

    def leave(self):
        """请假"""
        try:
            if self.incumbency():  # 判断是否在职
                info = input("请输入请假理由: ")
                if self.verify.enter_validation(info):
                    datas = {'employID': self.data.employID, 'name': self.data.username, 'phone': self.data.phone,
                             'info': info}
                    # 加入请假表
                    self.db.add_data('tb_leave', datas)
                    print("请假申请已经提交！")
                else:
                    print("请假理由不能为空！")
            else:
                print("您已离职！")
        except Exception as e:
            print(f"请假申请失败: \033[31m{e}\033[0m'")

    def leave_receipt(self):
        """请假回执"""
        try:
            if self.incumbency():
                result = self.db.select_data('tb_leave', self.data.condition)
                if result:
                    print(result)
                else:
                    print("您没有请过假！")
            else:
                print('您已离职！')
        except Exception as e:
            print(f"查询请假回执失败: \033[31m{e}\033[0m'")

    def sign_in(self):
        """签到"""
        try:
            if self.incumbency():  # 首先判断是否在职
                # 考勤次数加1
                attendance = self.incumbency()[0][6] + 1
                datas = {'attendance': attendance}
                self.db.update_data('tb_employee', datas, self.data.condition)
                print("签到成功！")
            else:
                print("您已经离职，不能签到！")
        except Exception as e:
            print(f"签到失败: \033[31m{e}\033[0m'")

    def show_personal(self):
        """查看个人信息"""
        try:
            if self.incumbency():
                print(f"""
                工号: {self.data.employID}
                姓名: {self.data.username}
                考勤: {self.incumbency()[0][5]}
                绩效: {self.incumbency()[0][6]}
                请假: {self.incumbency()[0][-3]}
                """)
            else:
                print("您已离职！")
        except Exception as e:
            print(f"查询个人信息失败: \033[31m{e}\033[0m'")
